import React from 'react'
import { changeNav } from '../../../actions'
import { connect } from 'react-redux'
import {
    Button, List, InputItem, Flex
    , WingBlank, WhiteSpace, Popup, Tag, Toast
} from 'antd-mobile'
import hhistory from '../../../history'
import { ajaxGet, ajaxPost } from 'wxAjaxUtil';
import styles from '../wxelm/mdConfig.less';

const Item = List.Item;
const Brief = Item.Brief;
let productCode = "100027";
let oldJtCode = '';
var oldmdcounts = 0;

// var cartData2 = { "productCode": "100009", "sellType": 2, "sellNum": 1, "flag": 1, "groupConfig": { "groupCode": "G000131", "groupName": "魏琴测试集团" }, "storeConfig": [{ "storeCode": "T000781", "storeName": "魏琴测试门店" }], "productConfigLabel": "子业务", "productConfig": [{ "label": "享付", "code": "100008", "value": "0.00" }], "purchaseDurationLabel": "购买时长", "purchaseDuration": 1, "serviceFeeLabel": "服务费（每门店每年）", "serviceFee": "0.00", "activationFeeLabel": "开通费（每店）", "activationFee": "0.00", "payableFee": "0.00" }
class OpenCd extends React.Component {
    constructor(props) {
        super(props);
        this.selectmd = this.selectmd.bind(this);
        this.putIntoCart = this.putIntoCart.bind(this);
        this.openNow = this.openNow.bind(this);
        this.state = {
            btnDisabled: false,
            note: '',
            totalPay: Number(0),
            accesskey:'',
            sercet:'',
            key:''
        };

    }

    //计算应付款总计
    countTotalPay() {
        const { wxSubProducts, wxzhctSubProduct, jtData, mdData } = this.props;
        console.log(222222222)
        console.log(mdData.length);
        switch (this.state.sellType) {    //1: 集团数， 2：门店数， 3：终端数
            case 2:
                this.setState({
                    totalPay: ((Number(this.state.serviceFee) + Number(this.state.activationFee)) * ((mdData && mdData.length) ? Number(mdData.length) : Number(0))).toFixed(2)
                })
                break;
            case 1:
            case 3:
                this.setState({
                    totalPay: ((Number(this.state.serviceFee) + Number(this.state.activationFee))).toFixed(2)
                });
                break;
            default:
                this.setState({
                    totalPay: Number(0).toFixed(2)
                });
        }
    }

    componentDidMount() {
        this.props.tochangeNav({
            title: "开通餐道外卖", rbtn: [
                <Button key="1" type="primary" inline size="small">购物车</Button>
            ]
        });
        //请求数据
        ajaxGet("/app/product/" + productCode).then(res => {
            if (res.code == 0) {
                this.state.serviceFee = res.data.pricingScheme[0].serviceFee;
                this.state.activationFee = res.data.pricingScheme[0].activationFee;
                this.state.sellType = res.data.pricingScheme[0].sellType;
                if (oldmdcounts != this.props.mdData.length) {
                    this.countTotalPay();
                }

            } else {
                Toast.fail('获取产品单价失败', 1);
            }
        });
    }




    //按钮点击
    btnClick(url, type) {
        const { wxSubProducts, wxzhctSubProduct, jtData, mdData } = this.props;
        var storeConfig = this.props.location.state.storeConfig;
        console.log(storeConfig);
        var cartData = {
            "productCode": productCode,
            "sellType": this.state.sellType,
            "sellNum": mdData.length,
            "flag": 1,  //1开通  2续费
            "groupConfig": {
                "groupCode": jtData.code,
                "groupName": jtData.name
            },
            "productConfig": [
                {
                    "label": "accesskey",
                    "code": "accesskey",
                    "value": this.state.accesskey
                },
                {
                    "label": "sercet",
                    "code": "sercet",
                    "value": this.state.sercet
                },
                {
                    "label": "key",
                    "code": "key",
                    "value": this.state.key
                }
            ],
            "storeConfig": storeConfig,
            "purchaseDurationLabel": "购买时长",
            "purchaseDuration": "1",
            "serviceFeeLabel": "服务费（每门店每年）",
            "serviceFee": this.state.serviceFee,
            "activationFeeLabel": "开通费（每店）",
            "activationFee": this.state.activationFee,
            "payableFee": this.state.totalPay,
            "remark": this.state.note
        };
        if (Object.keys(this.props.jtData).length == 0) {
            Toast.fail('请先去添加集团！', 1);
            return false;
        }
        if (Object.keys(this.props.mdData).length == 0) {
            Toast.fail('请先去添加门店！', 1);
            return false;
        }
        if (!this.props.location.state.storeConfig||Object.keys(this.props.location.state.storeConfig).length == 0) {
            Toast.fail('请先去配置门店！', 1);
            return false;
        }
        if(!this.state.accesskey||!this.state.sercet||!this.state.key){
            Toast.fail('请完整填写餐道密匙!',1);
            return false;
        }




        this.setState({ btnDisabled: true }); //将按钮变为不可用
        console.log(cartData);

        //发送ajax请求
        //立即开通
        if (type == 0) {
            ajaxPost(url, cartData).then(res => {
                if (res.code && res.code == "0") {
                    Toast.success('开通申请已提交', 1);
                } else {
                    Toast.fail('开通失败', 1);
                    this.setState({ btnDisabled: false });
                }
            })
        }
        //加入购物车
        if (type == 1) {
            ajaxPost(url, cartData).then(res => {
                if (res.code && res.code == "0") {
                    Toast.success('已加入购物车', 1);
                } else {
                    Toast.fail('加入购物车失败', 1);
                    this.setState({ btnDisabled: false });
                }
            })
        }
    }



    //加入购物车
    putIntoCart() {
        this.btnClick('app/shopping/cart', 1);
    }
    //立即开通
    openNow() {
        this.btnClick('app/product/open', 0);
    }
    //选择集团
    selectjt() {
        hhistory.push({ pathname: '/SelectGroup', state: { backRouter: '/cdOpen' } })
    }
    //选择门店
    selectmd() {
        if (Object.keys(this.props.jtData).length === 0) {
            Toast.fail('请先去添加集团！', 1);
        } else {
            oldJtCode = this.props.jtData.code;
            hhistory.push({ pathname: '/SelectDr', state: { backRouter: '/cdOpen' } })

        }
    }

    //门店配置
    mdconfig() {
        hhistory.push({ pathname: '/cdMdConfig', state: { backRouter: '/cdOpen' } });
    }

    render() {
        const { wxSubProducts, wxzhctSubProduct, jtData, mdData } = this.props;
        let storeItems = (oldJtCode != jtData.code || !mdData.length || mdData.length === 0) ? '' : mdData.map((item, index) => {
            return <Item key={index} thumb={item.logo} multipleLine>
                {item.name}<Brief>{item.code}</Brief>
            </Item>
        });

        return (
            <div>
                <List renderHeader={() => '选择开通商户'}>
                    <Item extra="选择集团" arrow="horizontal" onClick={this.selectjt}>
                        {(jtData == null || Object.keys(jtData).length === 0) ? '请选择集团' : <span><img src={jtData.logo} />{jtData.name}</span>}
                    </Item>
                    <Item extra="选择门店" arrow="horizontal" onClick={this.selectmd}>
                        共<span>{(oldJtCode != jtData.code || !mdData.length || mdData.length === 0) ? '0' : mdData.length}</span>个门店
			        </Item>
                    {storeItems}
                </List>
                <WhiteSpace size='md' styleName="yellow" />
                <Item extra="必填设置" arrow="horizontal" onClick={this.mdconfig}>门店配置</Item>
                <List renderHeader={() => '餐道密匙'}>
                    <Item><div><span>accesskey</span><input onBlur={(e) => { this.state.accesskey = e.target.value }} className={styles.input} type="text" placeholder="必填" /></div></Item>
                    <Item><div><span>Sercet</span><input onBlur={(e) => { this.state.sercet = e.target.value }} className={styles.input} type="text" placeholder="必填" /></div></Item>
                    <Item><div><span>Key</span><input onBlur={(e) => { this.state.key = e.target.value }} className={styles.input} type="text" placeholder="必填" /></div></Item>
                </List>
                <WhiteSpace size='md' styleName="yellow" />
                <List>
                    <InputItem placeholder="备注信息选填" onBlur={value => { this.state.note = value }}></InputItem>
                </List>
                <WhiteSpace size='md' styleName="yellow" />
                <List>
                    <Item>
                        <div>应付款总计<span>&yen;{Number(this.state.totalPay).toFixed(2)}</span></div>
                    </Item>
                </List>
                <WhiteSpace size="lg" />
                <WingBlank size="lg">
                    <Flex>
                        <Flex.Item>
                            <Button type="ghost" disabled={this.state.btnDisabled} onClick={this.putIntoCart}>加入购物车</Button>
                        </Flex.Item>
                        <Flex.Item>
                            <Button type="primary" disabled={this.state.btnDisabled} onClick={this.openNow}>提交申请</Button>
                        </Flex.Item>
                    </Flex>
                </WingBlank>
                <WhiteSpace size="lg" />
            </div>
        )
    }


}

const mapStateToProps = (state) => ({
    jtData: state.wxSmartdrs.jtData,
    mdData: state.wxSmartdrs.mdData
})
const mapDispatchToProps = (dispatch) => ({
    tochangeNav: navogj => dispatch(changeNav(navogj)),
})

export default connect(mapStateToProps, mapDispatchToProps)(OpenCd)